const gulp  = require('gulp');

//开启服务器
var connect = require('gulp-connect')
var watch = require('gulp-watch')
var livereload = require('gulp-livereload')
var browserSync = require('browser-sync')

//压缩html
var htmlClean = require('gulp-htmlclean')

//压缩image
var imageMin = require('gulp-imagemin')

//压缩js
var uglify = require('gulp-uglify')
var debug = require('gulp-strip-debug')

//压缩css

var cleanCss = require('gulp-clean-css')
var postCss = require('gulp-postcss')
var autoprefixer = require('autoprefixer')

//less->css
var less = require('gulp-less')

var folder = {
	src: 'src/',
	dist: 'dist/'
}

//判断当前环境变量   //开发环境
//export NODE_ENV=development
var devMod = process.env.NODE_ENV === 'development';
console.log(devMod)

gulp.task("html",function() {
	var page = gulp.src(folder.src + "html/*")
		if(!devMod){
			page.pipe(htmlClean())
		}
	page
		.pipe(connect.reload())
		.pipe(gulp.dest(folder.dist + "html/"))

			return Promise.resolve();

})
gulp.task("css", function() {
	var page =  gulp.src(folder.src + "css/*")
	 .pipe(less())
	 .pipe(postCss([autoprefixer()]))
	 if(!devMod){

		 page.pipe(cleanCss())
	 }
	 page
	 .pipe(connect.reload())
	 .pipe(gulp.dest(folder.dist + "css/"))
	return Promise.resolve();

})
gulp.task("js", function() {
	 var page = gulp.src(folder.src + "js/*")
		if(!devMod){
	    page.pipe(debug())
	    .pipe(uglify())
		}
		 page
		 .pipe(connect.reload())
		.pipe(gulp.dest(folder.dist + "js/"))
	return Promise.resolve();
})
gulp.task("images", function() {
	gulp.src(folder.src + "images/!*")
		.pipe(imageMin())
		.pipe(connect.reload())
		.pipe(gulp.dest(folder.dist + "images/"))
	return Promise.resolve();
})

gulp.task('server',function(){
	connect.server({
		port:'8888',
		livereload:true,

	})
})

gulp.task('watch', function(){
	livereload.listen()
		gulp.watch(folder.src + 'html/*',gulp.series('html',(cb) => {
			cb();
		})).on('change',() => {
			console.log('watch:文件已改变')
		})
		gulp.watch(folder.src + 'css/*',gulp.series('css'),(cb) => {
			cb();
		}).on('change',() => {
		console.log('watch:文件已改变')
		})
		gulp.watch(folder.src + 'images/*',gulp.series('images'),(cb) => {
			cb();
		}).on('change',() => {
			console.log('watch:文件已改变')
		})
		gulp.watch(folder.src + 'js/*',gulp.series('js'),(cb) => {
			cb();
		}).on('change',() => {
			console.log('watch:文件已改变')
		})



	//watch监听文件

})
gulp.task("default",gulp.series("html","css","js","images","server","watch"))



//less -> 自动添加css前缀 -> 压缩 -> css文件
// gulp.src()
// gulp.dest()
// gulp.task()
// gulp.watch()